import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { Project, Scene, Character } from '../types/project'
import { ElectronService } from '../services/electron.service'

export const useProjectStore = defineStore('project', () => {
  // 项目列表
  const projects = ref<Project[]>([])
  const currentProject = ref<Project | null>(null)
  const isProjectLoading = ref(false)
  const projectError = ref<string | null>(null)
  
  // 项目视图筛选
  const filter = ref({
    search: '',
    sortBy: 'updatedAt',
    sortOrder: 'desc' as 'asc' | 'desc',
    tags: [] as string[],
    status: [] as string[]
  })

  // 获取所有项目
  const fetchProjects = async () => {
    try {
      isProjectLoading.value = true
      projectError.value = null
      
      const response = await ElectronService.getProjects()
      if (response.success) {
        projects.value = response.projects
        return true
      } else {
        projectError.value = response.message || '获取项目失败'
        return false
      }
    } catch (error) {
      console.error('获取项目列表失败:', error)
      projectError.value = '获取项目时发生错误'
      return false
    } finally {
      isProjectLoading.value = false
    }
  }

  // 获取单个项目
  const fetchProject = async (id: string) => {
    try {
      isProjectLoading.value = true
      projectError.value = null
      
      const response = await ElectronService.getProject(id)
      if (response.success) {
        currentProject.value = response.project
        return true
      } else {
        projectError.value = response.message || '获取项目失败'
        return false
      }
    } catch (error) {
      console.error('获取项目失败:', error)
      projectError.value = '获取项目时发生错误'
      return false
    } finally {
      isProjectLoading.value = false
    }
  }

  // 创建新项目
  const createProject = async (projectData: Partial<Project>) => {
    try {
      isProjectLoading.value = true
      projectError.value = null
      
      const response = await ElectronService.createProject(projectData)
      if (response.success) {
        currentProject.value = response.project
        projects.value.push(response.project)
        return response.project
      } else {
        projectError.value = response.message || '创建项目失败'
        return null
      }
    } catch (error) {
      console.error('创建项目失败:', error)
      projectError.value = '创建项目时发生错误'
      return null
    } finally {
      isProjectLoading.value = false
    }
  }

  // 更新项目
  const updateProject = async (projectData: Partial<Project>) => {
    if (!projectData.id) {
      projectError.value = '项目ID不能为空'
      return false
    }
    
    try {
      isProjectLoading.value = true
      projectError.value = null
      
      const response = await ElectronService.updateProject(projectData)
      if (response.success) {
        // 更新当前项目
        if (currentProject.value?.id === projectData.id) {
          currentProject.value = { ...currentProject.value, ...response.project }
        }
        
        // 更新项目列表
        const index = projects.value.findIndex(p => p.id === projectData.id)
        if (index !== -1) {
          projects.value[index] = { ...projects.value[index], ...response.project }
        }
        
        return true
      } else {
        projectError.value = response.message || '更新项目失败'
        return false
      }
    } catch (error) {
      console.error('更新项目失败:', error)
      projectError.value = '更新项目时发生错误'
      return false
    } finally {
      isProjectLoading.value = false
    }
  }

  // 删除项目
  const deleteProject = async (id: string) => {
    try {
      isProjectLoading.value = true
      projectError.value = null
      
      const response = await ElectronService.deleteProject(id)
      if (response.success) {
        // 从项目列表中移除
        projects.value = projects.value.filter(p => p.id !== id)
        
        // 如果当前项目被删除，清空当前项目
        if (currentProject.value?.id === id) {
          currentProject.value = null
        }
        
        return true
      } else {
        projectError.value = response.message || '删除项目失败'
        return false
      }
    } catch (error) {
      console.error('删除项目失败:', error)
      projectError.value = '删除项目时发生错误'
      return false
    } finally {
      isProjectLoading.value = false
    }
  }

  // 筛选后的项目列表
  const filteredProjects = computed(() => {
    let result = [...projects.value]
    
    // 搜索筛选
    if (filter.value.search) {
      const searchLower = filter.value.search.toLowerCase()
      result = result.filter(p => 
        p.name.toLowerCase().includes(searchLower) || 
        (p.description && p.description.toLowerCase().includes(searchLower))
      )
    }
    
    // 标签筛选
    if (filter.value.tags.length > 0) {
      result = result.filter(p => 
        p.tags && filter.value.tags.some(tag => p.tags.includes(tag))
      )
    }
    
    // 状态筛选
    if (filter.value.status.length > 0) {
      result = result.filter(p => 
        filter.value.status.includes(p.status)
      )
    }
    
    // 排序
    result.sort((a, b) => {
      const sortField = filter.value.sortBy
      let aValue: any = a[sortField as keyof Project]
      let bValue: any = b[sortField as keyof Project]
      
      // 日期类型处理
      if (sortField === 'createdAt' || sortField === 'updatedAt') {
        aValue = new Date(aValue).getTime()
        bValue = new Date(bValue).getTime()
      }
      
      if (filter.value.sortOrder === 'asc') {
        return aValue > bValue ? 1 : -1
      } else {
        return aValue < bValue ? 1 : -1
      }
    })
    
    return result
  })

  // 保存场景
  const saveScene = async (scene: Partial<Scene>) => {
    if (!currentProject.value?.id) {
      projectError.value = '当前没有打开的项目'
      return null
    }
    
    try {
      projectError.value = null
      
      const response = await ElectronService.saveScene({
        ...scene,
        projectId: currentProject.value.id
      })
      
      if (response.success) {
        // 更新当前项目中的场景
        if (currentProject.value) {
          const sceneIndex = currentProject.value.scenes.findIndex(s => s.id === response.scene.id)
          
          if (sceneIndex !== -1) {
            // 更新现有场景
            currentProject.value.scenes[sceneIndex] = response.scene
          } else {
            // 添加新场景
            currentProject.value.scenes.push(response.scene)
          }
        }
        
        return response.scene
      } else {
        projectError.value = response.message || '保存场景失败'
        return null
      }
    } catch (error) {
      console.error('保存场景失败:', error)
      projectError.value = '保存场景时发生错误'
      return null
    }
  }

  // 保存角色
  const saveCharacter = async (character: Partial<Character>) => {
    if (!currentProject.value?.id) {
      projectError.value = '当前没有打开的项目'
      return null
    }
    
    try {
      projectError.value = null
      
      const response = await ElectronService.saveCharacter({
        ...character,
        projectId: currentProject.value.id
      })
      
      if (response.success) {
        // 更新当前项目中的角色
        if (currentProject.value) {
          const characterIndex = currentProject.value.characters.findIndex(c => c.id === response.character.id)
          
          if (characterIndex !== -1) {
            // 更新现有角色
            currentProject.value.characters[characterIndex] = response.character
          } else {
            // 添加新角色
            currentProject.value.characters.push(response.character)
          }
        }
        
        return response.character
      } else {
        projectError.value = response.message || '保存角色失败'
        return null
      }
    } catch (error) {
      console.error('保存角色失败:', error)
      projectError.value = '保存角色时发生错误'
      return null
    }
  }

  // 导出项目
  const exportProject = async (options: {
    format: string;
    quality: string;
    range: [number, number] | null;
    filename: string;
    directory: string;
  }) => {
    if (!currentProject.value?.id) {
      projectError.value = '当前没有打开的项目'
      return false
    }
    
    try {
      isProjectLoading.value = true
      projectError.value = null
      
      const response = await ElectronService.exportProject({
        projectId: currentProject.value.id,
        ...options
      })
      
      if (response.success) {
        return true
      } else {
        projectError.value = response.message || '导出项目失败'
        return false
      }
    } catch (error) {
      console.error('导出项目失败:', error)
      projectError.value = '导出项目时发生错误'
      return false
    } finally {
      isProjectLoading.value = false
    }
  }

  return {
    projects,
    currentProject,
    isProjectLoading,
    projectError,
    filter,
    filteredProjects,
    fetchProjects,
    fetchProject,
    createProject,
    updateProject,
    deleteProject,
    saveScene,
    saveCharacter,
    exportProject
  }
}) 